package com.baselibrary.view;

import android.content.Context;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.baselibrary.BaseConstant;
import com.baselibrary.MessageBus;
import com.baselibrary.R;
import com.baselibrary.databinding.ViewLocusVideoBinding;
import com.baselibrary.manager.SensorsDataManager;
import com.baselibrary.router.ActivityRouter;
import com.baselibrary.utils.ARouterUtils;
import com.baselibrary.utils.DoubleClickHelper;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.GlideUtils;
import com.baselibrary.utils.NetworkUtil;
import com.baselibrary.utils.ScreenUtils;
import com.baselibrary.utils.TimeUtil;
import com.baselibrary.utils.ToastUtils;
import com.bumptech.glide.Glide;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * @author:hanke 2022/4/27
 * desc:
 */
public class LocusVideoView extends LinearLayout {
    private ViewLocusVideoBinding mBinding;
    private boolean isPlay;
    private boolean isVoice;//true = 未静音
    private final LinkedHashMap<VideoView, MediaPlayer> mVideoLinkedMap = new LinkedHashMap<>();
    private VideoView mLatelyVideo;
    private String videoUrl;
    private Context mContext;
    private String name;
    private OnDoubleClickListener onDoubleClickListener;
    private OnVoiceClickListener mOnVoiceClickListener;

    public LocusVideoView(Context context) {
        super(context);
    }

    public LocusVideoView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public LocusVideoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public LocusVideoView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public boolean isVoice() {
        return isVoice;
    }

    public void setVoice(boolean voice) {
        isVoice = voice;
    }

    public void setData(Context context, String videoUrl, String coverUrl, int id, String uid, String name, OnVoiceClickListener listener) {
        this.videoUrl = videoUrl;
        this.mContext = context;
        this.name = name;
        this.mOnVoiceClickListener = listener;
        View view = LayoutInflater.from(context).inflate(R.layout.view_locus_video, this);
        view.setTag("layout/view_locus_video_0");
        mBinding = DataBindingUtil.bind(view);
        ScreenUtils.setVideoHeight(context, coverUrl, mBinding.ivLocusCover, mBinding.videoLocusVideo);
        GlideUtils.loadImg_228(context, coverUrl, mBinding.ivLocusCover);
        Glide.with(context).load(coverUrl)
                .placeholder(R.drawable.ic_def_hanxiang_228)
                .apply(mBinding.ivLocusMantle.setGaussBlur())
                .into(mBinding.ivLocusMantle);

        if (TextUtils.isEmpty(videoUrl)) {
            mBinding.rlVideo.setEnabled(false);
            mBinding.llLocusVideoError.setVisibility(View.VISIBLE);
            mBinding.pbVideoLoading.setVisibility(View.GONE);
        } else {
            mBinding.rlVideo.setEnabled(true);
            mBinding.llLocusVideoError.setVisibility(View.GONE);
            mBinding.videoLocusVideo.setVideoPath(videoUrl);
        }

        mBinding.videoLocusVideo.setOnPreparedListener(onPreparedListener);
        mBinding.videoLocusVideo.setOnErrorListener((mp, what, extra) -> {
            mBinding.videoLocusVideo.stopPlayback();
            ToastUtils.showShort(context, "视频播放出错");
            setErrorView();
            isPlay = false;
            return true;
        });
        mBinding.videoLocusVideo.setOnCompletionListener(mediaPlayer -> {
            mediaPlayer.start();
            mBinding.ivLocusCover.setVisibility(View.GONE);
            isPlay = true;
        });
        mBinding.rlVideo.setOnClickListener(new DoubleClickListener(new DoubleClickListener.DoubleClickCallBack() {
            @Override
            public void oneClick(View view) {
                if (!mBinding.videoLocusVideo.isPlaying()) {
                    startPlay();
                } else {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        goVideoDetails(id, uid);
                    }
                }
            }

            @Override
            public void doubleClick(View view) {
                if (onDoubleClickListener != null)
                    onDoubleClickListener.onDoubleClick();
            }
        }));
        mBinding.tvLocusErrorAgain.setOnClickListener(view1 -> setActive());
    }

    MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            isVoice(mp);
            mBinding.tvVideoDuration.setText(TimeUtil.formatMS(mp.getDuration() / 1000));
            mBinding.ivLocusVoice.setOnClickListener(v -> {
                isVoice = !isVoice;
                isVoice(mp);
                SensorsDataManager.Companion.getInstance().clickNoVoice(name);
                if (mOnVoiceClickListener != null) mOnVoiceClickListener.onVoiceClick(isVoice);
            });
            mp.setOnInfoListener((mp1, what, extra) -> {
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    //真正渲染第一帧
                    mBinding.ivLocusCover.setVisibility(View.GONE);
                    mBinding.pbVideoLoading.setVisibility(View.GONE);
                    mBinding.ivLocusPlay.setVisibility(View.GONE);
                }
                return true;
            });
        }
    };

    private void startPlay() {
        isPlay = true;
        if (mLatelyVideo != null && mLatelyVideo.isPlaying()) {
            mLatelyVideo.pause();
        }

        mLatelyVideo = mBinding.videoLocusVideo;
        mBinding.videoLocusVideo.start();

        mBinding.videoLocusVideo.setOnPreparedListener(onPreparedListener);
        if (mVideoLinkedMap.containsKey(mBinding.videoLocusVideo)) {
            if (mVideoLinkedMap.get(mBinding.videoLocusVideo) != null) {
                try {
                    Objects.requireNonNull(mVideoLinkedMap.get(mBinding.videoLocusVideo)).setVolume(isVoice ? 1f : 0f, isVoice ? 1f : 0f);
                    mBinding.ivLocusVoice.setBackgroundResource(isVoice ? R.drawable.icon_voice_on : R.drawable.icon_voice_off);
                } catch (Exception e) {
                    e.getMessage();
                }
            }
        }
        mBinding.ivLocusPlay.setVisibility(VISIBLE);
        mBinding.llLocusVideoError.setVisibility(GONE);
        mBinding.pbVideoLoading.setVisibility(View.VISIBLE);
        if (mBinding.videoLocusVideo.getCurrentPosition() > 0) {
            mBinding.ivLocusCover.setVisibility(View.GONE);
            mBinding.pbVideoLoading.setVisibility(View.GONE);
        }
    }

    private void pausePlay() {
        isPlay = false;
        mBinding.videoLocusVideo.pause();
        mBinding.ivLocusCover.setVisibility(View.VISIBLE);
        mBinding.pbVideoLoading.setVisibility(View.GONE);


    }

    private void isVoice(MediaPlayer mp) {
        try {
            mVideoLinkedMap.put(mBinding.videoLocusVideo, mp);
            mp.setVolume(isVoice ? 1f : 0f, isVoice ? 1f : 0f);
            mBinding.ivLocusVoice.setBackgroundResource(isVoice ? R.drawable.icon_voice_on : R.drawable.icon_voice_off);
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public void setActive() {
        if (!TextUtils.isEmpty(videoUrl) && isActivePlay(mContext) && !mBinding.videoLocusVideo.isPlaying()) {
            mBinding.videoLocusVideo.post(this::startPlay);
        } else {
            if (!NetworkUtil.isConnected(getContext())) {
                ToastUtils.showShort(getContext().getApplicationContext(), getResources().getString(R.string.common_network));
            }
        }
    }

    public void deactivate() {
        if (mBinding.videoLocusVideo.isPlaying()) {
            mBinding.videoLocusVideo.post(this::pausePlay);
        }
    }

    public View getAutoplayView() {
        return mBinding.videoLocusVideo;
    }

    private boolean isActivePlay(Context context) {
        int mNetWorkType = NetworkUtil.getNetWorkType(context);
        boolean isConnected = NetworkUtil.isAvailable(context);
        return isConnected && mNetWorkType == NetworkUtil.NETWORK_WIFI;
    }

    public void setErrorView() {
        if (!NetworkUtil.isConnected(getContext())) {
            mBinding.tvLocusError.setText("哎呀，网络好像出了点问题！");
        } else {
            mBinding.tvLocusError.setText("该视频无法播放！");
        }
        mBinding.ivLocusPlay.setVisibility(GONE);
        mBinding.pbVideoLoading.setVisibility(GONE);
        mBinding.llLocusVideoError.setVisibility(VISIBLE);
    }

    public void goVideoDetails(int id, String uid) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", id);
        hashMap.put("isOpenComment", false);
        hashMap.put("JumpType", 2);
        hashMap.put("bid", uid);
        hashMap.put("source", BaseConstant.POINT_DYNAMIC_FOLLOW);
        EventBusUtils.sendNotify(MessageBus.msgid_jump_to_detail);
        ARouterUtils.jump(ActivityRouter.ACTIVITY.READ_VIDEO_DETAIL, hashMap);
    }

    public void setOnDoubleClickListener(OnDoubleClickListener onDoubleClickListener) {
        this.onDoubleClickListener = onDoubleClickListener;
    }

    public interface OnDoubleClickListener {
        void onDoubleClick();
    }

    public interface OnVoiceClickListener {
        void onVoiceClick(boolean voice);
    }
}
